/**
 * 黑蝎营销策划有限公司网站主JS文件
 */

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
  // 初始化动画
  initAnimation();
  
  // 导航菜单
  initNavigation();
  
  // 滚动效果
  initScrollEffects();
  
  // 响应式处理
  handleResponsive();
  
  // 初始化轮播
  initSwipers();
});

/**
 * 初始化动画效果
 */
function initAnimation() {
  // 检查是否有WOW.js
  if (typeof WOW !== 'undefined') {
    new WOW({
      boxClass: 'animate',
      animateClass: 'animated',
      offset: 100,
      mobile: true,
      live: true
    }).init();
  }
  
  // 自动滚动内容
  const autoScrollContainers = document.querySelectorAll('.auto-scroll-container');
  if (autoScrollContainers.length > 0) {
    autoScrollContainers.forEach(container => {
      const wrapper = container.querySelector('.auto-scroll-wrapper');
      const items = container.querySelectorAll('.auto-scroll-item');
      
      if (items.length > 1) {
        // 复制第一个元素到末尾，实现无缝循环
        const firstItemClone = items[0].cloneNode(true);
        wrapper.appendChild(firstItemClone);
        
        let currentIndex = 0;
        const totalItems = items.length + 1; // 包括克隆的元素
        
        function scrollToNext() {
          currentIndex = (currentIndex + 1) % totalItems;
          
          // 平滑过渡
          wrapper.style.transition = 'transform 0.8s ease';
          wrapper.style.transform = `translateY(-${currentIndex * 100}%)`;
          
          // 当滚动到克隆元素时，在过渡结束后无缝跳回第一个元素
          if (currentIndex === totalItems - 1) {
            setTimeout(() => {
              wrapper.style.transition = 'none';
              wrapper.style.transform = 'translateY(0)';
              currentIndex = 0;
            }, 800);
          }
        }
        
        // 每5秒切换一次
        setInterval(scrollToNext, 5000);
      }
    });
  }
}

/**
 * 初始化导航菜单
 */
function initNavigation() {
  // 移动端菜单切换
  const mobileNavToggle = document.querySelector('.mobile-nav-toggle');
  const navMenu = document.querySelector('.nav-menu');
  
  if (mobileNavToggle && navMenu) {
    mobileNavToggle.addEventListener('click', function() {
      this.classList.toggle('active');
      navMenu.classList.toggle('active');
    });
  }
  
  // 添加滚动时导航栏样式变化
  window.addEventListener('scroll', function() {
    const header = document.querySelector('header');
    if (header) {
      if (window.scrollY > 100) {
        header.classList.add('header-scrolled');
      } else {
        header.classList.remove('header-scrolled');
      }
    }
  });
}

/**
 * 初始化滚动效果
 */
function initScrollEffects() {
  // 数字计数器
  const counterSection = document.querySelector('.counter-section');
  if (counterSection) {
    const counters = document.querySelectorAll('.counter');
    let counted = false;
    
    window.addEventListener('scroll', function() {
      if (isInViewport(counterSection) && !counted) {
        counters.forEach(counter => {
          const target = +counter.getAttribute('data-target');
          const duration = 2000; // 动画持续时间（毫秒）
          const step = target / (duration / 16); // 假设60fps，每帧增加的值
          
          let current = 0;
          const updateCounter = () => {
            if (current < target) {
              current += step;
              counter.textContent = Math.floor(current);
              requestAnimationFrame(updateCounter);
            } else {
              counter.textContent = target;
            }
          };
          
          updateCounter();
        });
        
        counted = true;
      }
    });
  }
  
  // 滚动到顶部按钮
  const scrollTopBtn = document.querySelector('.back-to-top');
  if (scrollTopBtn) {
    window.addEventListener('scroll', function() {
      if (window.scrollY > 300) {
        scrollTopBtn.classList.add('active');
      } else {
        scrollTopBtn.classList.remove('active');
      }
    });
    
    scrollTopBtn.addEventListener('click', function() {
      window.scrollTo({
        top: 0,
        behavior: 'smooth'
      });
    });
  }
  
  // 滚动显示元素
  const scrollRevealElements = document.querySelectorAll('.scroll-reveal');
  if (scrollRevealElements.length > 0) {
    const observer = new IntersectionObserver((entries) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          entry.target.classList.add('active');
          observer.unobserve(entry.target);
        }
      });
    }, {
      threshold: 0.1
    });
    
    scrollRevealElements.forEach(element => {
      observer.observe(element);
    });
  }
}

/**
 * 响应式处理
 */
function handleResponsive() {
  // 服务轮播
  initServiceCarousel();
  
  // 窗口大小变化时重新初始化
  window.addEventListener('resize', function() {
    initServiceCarousel();
  });
}

/**
 * 初始化服务轮播
 */
function initServiceCarousel() {
  const servicesCards = document.querySelector('.services-cards');
  const prevBtn = document.getElementById('services-prev');
  const nextBtn = document.getElementById('services-next');
  
  if (servicesCards && prevBtn && nextBtn) {
    const cards = servicesCards.querySelectorAll('.service-card');
    
    // 复制前几个卡片添加到末尾，实现无缝循环
    const visibleCards = getVisibleCards();
    for (let i = 0; i < visibleCards; i++) {
      const clone = cards[i].cloneNode(true);
      servicesCards.appendChild(clone);
    }
    
    const cardWidth = cards[0].offsetWidth + 20; // 卡片宽度 + 间距
    let currentPosition = 0;
    const totalCards = cards.length + visibleCards;
    
    // 移动到指定位置
    const moveTo = (position, transition = true) => {
      currentPosition = position;
      servicesCards.style.transition = transition ? 'transform 0.5s ease' : 'none';
      servicesCards.style.transform = `translateX(-${position}px)`;
    };
    
    // 下一个
    nextBtn.addEventListener('click', function() {
      if (currentPosition < (cards.length) * cardWidth) {
        moveTo(currentPosition + cardWidth);
      } else {
        // 无缝循环：快速回到开始位置
        moveTo(0, false);
        // 添加延时，确保无缝
        setTimeout(() => {
          moveTo(cardWidth);
        }, 10);
      }
    });
    
    // 上一个
    prevBtn.addEventListener('click', function() {
      if (currentPosition > 0) {
        moveTo(currentPosition - cardWidth);
      } else {
        // 无缝循环：快速跳到末尾
        moveTo(cards.length * cardWidth, false);
        // 添加延时，确保无缝
        setTimeout(() => {
          moveTo((cards.length - 1) * cardWidth);
        }, 10);
      }
    });
    
    // 自动轮播
    let autoplayInterval = setInterval(() => {
      nextBtn.click();
    }, 6000);
    
    // 鼠标悬停时暂停自动轮播
    servicesCards.addEventListener('mouseenter', () => {
      clearInterval(autoplayInterval);
    });
    
    // 鼠标离开时恢复自动轮播
    servicesCards.addEventListener('mouseleave', () => {
      autoplayInterval = setInterval(() => {
        nextBtn.click();
      }, 6000);
    });
  }
}

/**
 * 初始化所有Swiper轮播
 */
function initSwipers() {
  // Banner轮播
  if (document.querySelector('.banner-swiper')) {
    new Swiper('.banner-swiper', {
      slidesPerView: 1,
      spaceBetween: 0,
      loop: true,
      loopAdditionalSlides: 3, // 添加额外的幻灯片以确保无缝循环
      autoplay: {
        delay: 5000,
        disableOnInteraction: false,
      },
      pagination: {
        el: '.swiper-pagination',
        clickable: true,
      },
      effect: 'fade',
      fadeEffect: {
        crossFade: true
      },
    });
  }
  
  // 合作伙伴轮播
  if (document.querySelector('.partners-slider .swiper-container')) {
    new Swiper('.partners-slider .swiper-container', {
      slidesPerView: 5,
      spaceBetween: 30,
      loop: true,
      loopAdditionalSlides: 5, // 添加额外的幻灯片以确保无缝循环
      speed: 800,
      autoplay: {
        delay: 3000,
        disableOnInteraction: false,
      },
      breakpoints: {
        320: {
          slidesPerView: 2,
          spaceBetween: 20
        },
        768: {
          slidesPerView: 3,
          spaceBetween: 30
        },
        992: {
          slidesPerView: 5,
          spaceBetween: 30
        }
      }
    });
  }
}

/**
 * 获取可见卡片数量
 */
function getVisibleCards() {
  const width = window.innerWidth;
  if (width < 576) {
    return 1;
  } else if (width < 992) {
    return 2;
  } else {
    return 3;
  }
}

/**
 * 检查元素是否在视口中
 */
function isInViewport(element) {
  const rect = element.getBoundingClientRect();
  return (
    rect.top <= (window.innerHeight || document.documentElement.clientHeight) &&
    rect.bottom >= 0
  );
}

/**
 * 项目筛选功能
 */
function filterPortfolio(category) {
  const items = document.querySelectorAll('.portfolio-item');
  
  items.forEach(item => {
    if (category === 'all' || item.classList.contains(category)) {
      item.style.display = 'block';
    } else {
      item.style.display = 'none';
    }
  });
}

/**
 * 视频播放功能
 */
function initVideoPlayer() {
  const videoContainer = document.querySelector('.video-container');
  if (videoContainer) {
    videoContainer.addEventListener('click', function() {
      const videoModal = document.createElement('div');
      videoModal.className = 'video-modal';
      videoModal.innerHTML = `
        <div class="video-modal-content">
          <span class="close-video">&times;</span>
          <video controls autoplay>
            <source src="videos/company-intro.mp4" type="video/mp4">
            您的浏览器不支持视频播放。
          </video>
        </div>
      `;
      document.body.appendChild(videoModal);
      
      // 关闭视频
      const closeBtn = videoModal.querySelector('.close-video');
      closeBtn.addEventListener('click', function() {
        document.body.removeChild(videoModal);
      });
    });
  }
}

// 页面加载完成后初始化视频播放器
document.addEventListener('DOMContentLoaded', initVideoPlayer);